package vip.zhenzicheng.bio;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * 单线程版 BIO 通信的服务端 因为只有一个主线程处理连接所以存在问题
 *
 * @author zhenzicheng
 * @date: 2022-06-01 14:37
 */
public class ServerSingle {
  private static final Logger LOG = Logger.getLogger(ServerSingle.class.getSimpleName());

  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = new ServerSocket();
    // 表示服务端在哪个端口上监听
    serverSocket.bind(new InetSocketAddress(8888));
    LOG.info("Start Server......");
    int connectCount = 0;
    try {
      while (true) {
        // 阻塞直到等到连接
        Socket socket = serverSocket.accept();

        LOG.info("accept client socket ...... total=>" + ++connectCount);
        // 实例化与客户端通信的输入输出流
        try (
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream())) {
          // 接收客户端的输出，也就是服务器的输入
          String msg = inputStream.readUTF();
          LOG.info("Accept client message: " + msg);

          // 服务器的输出，也就是客户端的输入
          outputStream.writeUTF("got msg:{" + msg + "}");
          outputStream.flush();
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (socket != null) {
            socket.close();
          }
        }
      }
    } finally {
      serverSocket.close();
    }

  }
}
